#!/bin/bash
# Hive元数据监控系统安装脚本

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

echo_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

echo_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then 
    echo_error "请使用root用户或sudo执行此脚本"
    exit 1
fi

# 配置变量
INSTALL_DIR="/opt/hive-metadata-monitor"
LOG_DIR="/var/log/hive-metadata-monitor"
RUN_DIR="/var/run/metadata-monitor"
USER="hadoop"
GROUP="hadoop"

echo_info "开始安装Hive元数据监控系统..."

# 1. 检查Python版本
echo_info "检查Python版本..."
if ! command -v python3 &> /dev/null; then
    echo_error "未找到Python3，请先安装Python 3.8+"
    exit 1
fi

PYTHON_VERSION=$(python3 --version | awk '{print $2}')
echo_info "Python版本: $PYTHON_VERSION"

# 2. 创建目录
echo_info "创建目录..."
mkdir -p "$INSTALL_DIR"
mkdir -p "$LOG_DIR"
mkdir -p "$RUN_DIR"

# 3. 复制文件
echo_info "复制文件到安装目录..."
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cp -r "$SCRIPT_DIR"/* "$INSTALL_DIR/"

# 4. 创建虚拟环境
echo_info "创建Python虚拟环境..."
cd "$INSTALL_DIR"
python3 -m venv venv

# 5. 安装依赖
echo_info "安装Python依赖..."
source venv/bin/activate
pip install --upgrade pip
pip install -r short_term/requirements.txt
deactivate

# 6. 配置文件检查
if [ ! -f "$INSTALL_DIR/config/config.yaml" ]; then
    echo_warn "未找到config.yaml，从示例文件创建..."
    cp "$INSTALL_DIR/config/config.example.yaml" "$INSTALL_DIR/config/config.yaml"
    echo_warn "请编辑 $INSTALL_DIR/config/config.yaml 配置文件"
fi

# 7. 创建用户和组（如果不存在）
if ! id "$USER" &>/dev/null; then
    echo_info "创建用户: $USER"
    useradd -r -s /bin/bash "$USER"
fi

# 8. 设置权限
echo_info "设置文件权限..."
chown -R "$USER:$GROUP" "$INSTALL_DIR"
chown -R "$USER:$GROUP" "$LOG_DIR"
chown -R "$USER:$GROUP" "$RUN_DIR"
chmod +x "$INSTALL_DIR"/deploy/*.sh

# 9. 安装systemd服务
echo_info "安装systemd服务..."

# 元数据监控服务
cat > /etc/systemd/system/hive-metadata-monitor.service <<EOF
[Unit]
Description=Hive Metadata Monitor Service
After=network.target

[Service]
Type=simple
User=$USER
Group=$GROUP
WorkingDirectory=$INSTALL_DIR
ExecStart=$INSTALL_DIR/venv/bin/python short_term/metadata_monitor.py
Restart=always
RestartSec=10
StandardOutput=append:$LOG_DIR/monitor.log
StandardError=append:$LOG_DIR/error.log

# 资源限制
LimitNOFILE=65536
MemoryLimit=512M

[Install]
WantedBy=multi-user.target
EOF

# Binlog监控服务
cat > /etc/systemd/system/hive-binlog-monitor.service <<EOF
[Unit]
Description=Hive Binlog Monitor Service
After=network.target

[Service]
Type=simple
User=$USER
Group=$GROUP
WorkingDirectory=$INSTALL_DIR
ExecStart=$INSTALL_DIR/venv/bin/python short_term/binlog_monitor.py
Restart=always
RestartSec=10
StandardOutput=append:$LOG_DIR/binlog-monitor.log
StandardError=append:$LOG_DIR/binlog-error.log

# 资源限制
LimitNOFILE=65536
MemoryLimit=512M

[Install]
WantedBy=multi-user.target
EOF

# 10. 重载systemd
echo_info "重载systemd配置..."
systemctl daemon-reload

# 11. 配置日志轮转
echo_info "配置日志轮转..."
cat > /etc/logrotate.d/hive-metadata-monitor <<EOF
$LOG_DIR/*.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 0644 $USER $GROUP
    sharedscripts
    postrotate
        systemctl reload hive-metadata-monitor > /dev/null 2>&1 || true
        systemctl reload hive-binlog-monitor > /dev/null 2>&1 || true
    endscript
}
EOF

echo_info "安装完成！"
echo ""
echo "============================================"
echo "下一步操作："
echo "1. 编辑配置文件："
echo "   vi $INSTALL_DIR/config/config.yaml"
echo ""
echo "2. 启动服务（选择一种监控模式）："
echo "   - 元数据库监控："
echo "     systemctl enable hive-metadata-monitor"
echo "     systemctl start hive-metadata-monitor"
echo ""
echo "   - Binlog监控："
echo "     systemctl enable hive-binlog-monitor"
echo "     systemctl start hive-binlog-monitor"
echo ""
echo "3. 查看服务状态："
echo "   systemctl status hive-metadata-monitor"
echo "   systemctl status hive-binlog-monitor"
echo ""
echo "4. 查看日志："
echo "   tail -f $LOG_DIR/monitor.log"
echo "   tail -f $LOG_DIR/binlog-monitor.log"
echo "============================================"

